package com.briup.pts.service.impl;

import cn.hutool.extra.qrcode.QrCodeUtil;
import com.briup.pts.config.property.QrcodeProperty;
import com.briup.pts.domain.bean.Animal;
import com.briup.pts.domain.vo.AnimalVO;
import com.briup.pts.mapper.AnimalMapper;
import com.briup.pts.service.AnimalService;
import com.briup.pts.service.QrcodeService;
import com.briup.pts.service.UploadService;
import com.briup.pts.utils.CustomMultipartFile;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;

@Service
@RequiredArgsConstructor
public class AnimalServiceImpl implements AnimalService {

    private final AnimalMapper animalMapper;
    private final QrcodeProperty property;
    private final UploadService uploadService;
    private final QrcodeService qrcodeService;

    @Override
    public PageInfo<AnimalVO> pageQuery(Integer pageNum, Integer pageSize,
                                        String aHealthy, String aGender) {
        try (Page<AnimalVO> ignored = PageHelper.startPage(pageNum,pageSize)){
            // 根据条件查询数据
           List<AnimalVO> animalVOS =  animalMapper.queryByConditional(aHealthy,aGender);
           Page<AnimalVO> voPage = (Page<AnimalVO>) animalVOS;
           return new PageInfo<>(voPage);
        }
    }

    @Override
    public AnimalVO queryById(String animalId) {
        // 根据id查询动物及其对应栏圈、批次等信息
        return animalMapper.queryById(animalId);
    }

    @Override
    @Transactional
    public void deleteById(String animalId) {

    }

    @Override
    @Transactional
    public void batchDelete(List<String> animalIds) {
        // 遍历需要删除动物的id集合，一个一个删除
        animalIds.forEach(this::deleteById);
    }

    @Override
    @Transactional
    public void saveOrUpdate(Animal animal) {

    }

    @Override
    public void qrCode(String animalId) {
        // 根据id生成对应的二维码信息
        File file = new File(String.format(property.getPath(),animalId));
        QrCodeUtil.generate(String.format(property.getContent(),animalId),300,300,file);
        // 将文件放入到nginx中，可以获取到二维码的url地址
        String url = uploadService.upload(
                new CustomMultipartFile(file,"image/png"));
        // 将二维码的url地址存入到数据库中
        qrcodeService.addQrcode(animalId,url);
        // 将二维码文件删除
        boolean ignored = file.delete();
    }
}
